/* Reusable Command to perform select statements in salesforce */
package poler.control.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.salesforce.AsyncResponder;
	import com.salesforce.results.QueryResult;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.IResponder;
	
	import poler.classes.AbstractCommand;
	import poler.control.events.SelectEvent;
	import poler.model.ModelLocator;

	
	
	public class SelectCmd extends AbstractCommand implements ICommand, IResponder
	{
		private var _amLocator:ModelLocator = ModelLocator.getInstance();
		private var cFunction:Function;
		private var resObject : ArrayCollection;  
	
		public function execute(event:CairngormEvent):void
		{
			
			resObject = new ArrayCollection();
			
			if((event as SelectEvent).Callback != null){
				cFunction = (event as SelectEvent).Callback;
			}	
			// 
			var sQuery:String = (event as SelectEvent).SQuery;
			_amLocator.Apex.query(sQuery,new AsyncResponder(qResult));
		}
		private function qResult(qr:QueryResult):void{
        	
        	if(qr.size > 0){
        		for(var i:int = 0;i < qr.records.length;i++){
        			resObject.addItem(qr.records[i]);
        		}
        	}
        	if(qr.done){
        		result(resObject);
        	}else{
        		_amLocator.Apex.queryMore(qr.queryLocator,new AsyncResponder(qResult));
        	}
        }
		public function result(data:Object):void
		{			
			if(cFunction != null){
				cFunction(data);
			}
			//
			//
		}
		
	//	
	}
}